<script lang="ts" setup>
import type { SysConfig } from '#/api/system/sysconfig';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { addConfig, editConfig, getConfig } from '#/api/system/sysconfig';
import { $t } from '#/locales';

import { formSchema } from '../data';

const emit = defineEmits(['success']);

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: formSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = await formApi.getValues<SysConfig>();

    try {
      await (data?.configId ? editConfig(data) : addConfig(data));
      modalApi.close();
      emit('success');
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData();
    modalApi.setState({
      title: data.configId
        ? $t('ui.actionTitle.edit', [$t('config.config')])
        : $t('ui.actionTitle.create', [$t('config.config')]),
    });
    if (data?.configId) {
      const client = await getConfig(data?.configId);
      formApi.setValues(client, false);
    }
  },
});
</script>

<template>
  <Modal>
    <Form class="mx-4" />
  </Modal>
</template>
